package com.cg.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cg.utils.R;
import com.cg.utils.UploadUtil;

@Controller
@RequestMapping("/upload/")
public class UploadController {
	/**访问地址*/
	@Value("${global.upload.path}")
	private String path;
	/**存放地址*/
	@Value("${global.upload.docBase}")
	private String docBase;
	@Autowired
	private UploadUtil uploadUtil;

	/**
	 * 上传图片
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "uploadImg.do")
	@ResponseBody
	public R uploadImg(HttpServletRequest request) {
		final Map<String, Object> result = new HashMap<String, Object>();
		List<String> filepath = uploadUtil.upload(request,docBase, path,"appmenu/");
		result.put("filepath", filepath);
		return R.ok(result);
	}

	/**
	 * 上传文件(注意:前端需要传默认参数:name="files",或者加注解@RequestParam("files")指定参数名)
	 * @param request
	 * @param type
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "uploadFile.do")
	@ResponseBody
	public R uploadFile(MultipartFile[] files, HttpServletRequest request) {
		final Map<String, Object> result = new HashMap<String, Object>();
		// 判断file数组不能为空并且长度大于0
		if (files != null && files.length > 0) {
			// 循环获取file数组中得文件
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				// 判断文件是否为空
				if (!file.isEmpty()) {
					String fileName = file.getOriginalFilename();
					// 文件后缀
					String suffixes = fileName.substring(fileName.lastIndexOf("."), fileName.length());
					// 重命名文件
					String nowName = uploadUtil.getNewName(suffixes);

					final ByteArrayOutputStream fileStream = new ByteArrayOutputStream();
					// 存放位置
					String savepath = uploadUtil.getFilePath(docBase, nowName);
					try {
						// 复制文件内容
						IOUtils.copy(file.getInputStream(), fileStream);
						// 复制文件
						FileUtils.copyInputStreamToFile(new ByteArrayInputStream(fileStream.toByteArray()), new File(savepath));
					} catch (Exception e) {
						return R.error("文件上传失败");
					}
					result.put("url", uploadUtil.getFilePath(path, nowName));
				} else {
					return R.error("请选择logo");
				}
			}
		}
		return R.ok();
	}

}
